package com.jiyinit.web.core.business.controller;

import com.jiyinit.core.framework.base.entity.ResponseDto;
import com.jiyinit.core.framework.base.util.Check;
import com.jiyinit.core.framework.base.util.LogUtil;
import com.jiyinit.web.core.business.entity.TabCoreUserEntity;
import com.jiyinit.web.core.business.service.UserServiceImpl;
import com.jiyinit.web.core.common.config.PropertyPlaceholderConfigurer;
import com.jiyinit.web.core.common.token.Token;
import com.jiyinit.web.core.common.util.HttpClientUtil;
import com.jiyinit.web.core.common.util.UserUtil;
import com.jiyinit.web.core.common.vo.CurrentUserVo;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.CharArrayBuffer;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.apache.taglibs.standard.tag.common.core.Util.URLEncode;

/**
 * <p></p>
 * <p>
 * <PRE>
 * <BR>	修改记录
 * <BR>-----------------------------------------------
 * <BR>	修改日期			修改人			修改内容
 * </PRE>
 *
 * @author lishaochuan
 * @version 1.0
 * @date 2017/4/10 18:00
 * @since 1.0
 */
@Controller
@RequestMapping("/")
public class LoginController {




    /**
     * 日志对象
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);

    @Resource(name = "core.userServiceImpl")
    private UserServiceImpl userService;

    /**
     * 跳转登录页面
     * @author lishaochuan
     * @create 2017/4/11 12:27
     * @param
     * @return
     */
    @RequestMapping(value = "/login")
    public String userLogin(HttpServletRequest request, Model model) {
        return "login/login";
    }

    /**
     * 登录
     * @author zhaolaiwei
     * @create 2017/4/12 9:28
     * @param request
     * @param model
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST,value = "/login")
    public ResponseEntity<ResponseDto> login(HttpServletRequest request, Model model){

       /* String str1="{\"productTag\":\"OPL9\",\"insureTag\":\"\",\"flyFund\":false,\"fuelTax\":0,\"childFuelTax\":0,\"constructionFee\":0,\"printPrice\":15,\"yPrice\":0,\"childPrintPrice\":0,\"discount\":\"0.6\",\"policyType\":0,\"policyId\":0,\"type\":\"\",\"contact\":\"武士敏\",\"contactPreNum\":\"86\",\"contactMob\":\"17703212540\",\"contactEmail\":\"346610648@qq.com\",\"invoiceType\":2,\"receiverTitle\":\"北京冀银科技有限公司\",\"receiverType\":3,\"taxpayerId\":\"91110102MA0025802T\",\"sjr\":\"武士敏\",\"sjrPhone\":\"17703212540\",\"address\":\"河北省石家庄平安南大街79号\",\"xcd\":\"\",\"xcdMethod\":\"\",\"xcdPrice\":0,\"bxInvoice\":\"\",\"flightInfo\":{\"flightNum\":\"JR1518\",\"gx\":\"\",\"flightType\":1,\"stopInfo\":0,\"deptAirportCode\":\"AXF\",\"arriAirportCode\":\"INC\",\"deptCity\":\"阿拉善左旗\",\"arriCity\":\"银川\",\"deptDate\":\"2019-01-31\",\"deptTime\":\"08:30\",\"arriTime\":\"09:05\",\"cabin\":\"G\",\"childCabin\":\"Y\"},\"passengerCount\":1,\"passengers\":[{\"name\":\"武士敏\",\"ageType\":0,\"cardType\":\"NI\",\"cardNo\":\"130129199003012540\",\"sex\":0,\"birthday\":\"1990-03-01\",\"passengerPriceTag\":\"OPL9\",\"bx\":false,\"flightDelayBx\":false,\"flightDelayType\":null,\"flightDelayCode\":null,\"tuipiaoBx\":false,\"tuipiaoCode\":null}],\"bookingTag\":\"XDRNIwpYfS4AAdAwiWzjhZsD1QEQO0onRjePAA==\",\"xth\":\"\",\"qt\":\"49935a9c-a781-489b-9bdc-647425895d66\",\"source\":\"web.baituor.2728\",\"clientSite\":\"xos.trade.qunar.com\",\"useBonus\":false}";
        System.out.println(str1);
        String enstr = URLEncode(str1,"utf-8");
        System.out.println(enstr);

        try {
            String destr = URLDecoder.decode(enstr, "utf-8");
            System.out.println(destr);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }*/
       /* //此处是应用级的参数 具体详见接口文档 通过前端页面传过来的对象 转换为json串即可
        String params = "{\"date\":\"2018-12-31\",\"arr\":\"SHA\",\"dpt\":\"PEK\",\"ex_track\":\"chailv\"}";

        String QUNAR_BASE_URL = (String) PropertyPlaceholderConfigurer.getContextProperty("QUNAR_BASE_URL");
        String Tag = "flight.national.supply.sl.searchflight";

        Map<String, String> paramMap = new HashMap();

        try {
            paramMap = Token.getQunarSign(Tag, params);
            paramMap.put("params",params);
//          paramMap.put("params",URLEncode(params,"utf-8") );

            String result = HttpClientUtil.doPost(QUNAR_BASE_URL, paramMap);
            LogUtil.info(LOGGER, "str:{}", result);
        } catch (Exception e) {
            LogUtil.error(LOGGER, "do request error:{}", e);
        }
*/


        String loginName = (String)request.getParameter("loginName");
        String password = (String)request.getParameter("password");
     //   HttpSession session = request.getSession();
        LogUtil.info(LOGGER, "loginName:{},password:{}", loginName,password);
        TabCoreUserEntity tabCoreUser = userService.login(loginName, password);
        if(!Check.isNullObj(tabCoreUser)){
            UserUtil.setUser2Session(new CurrentUserVo(tabCoreUser));
            /**
             * 该账号已经被登陆
             */
//            if(null != SessionListener.sessionMap.get( tabCoreUser.getUserName() ))
//            {
//                /**
//                 * 将已经登陆的信息拿掉,将新的用户登录信息放进去
//                 */
//              //  ForceLogoutUtils.forceUserLogout(tabCoreUser.getUserName());
//
//                // SessionListener.sessionMap.put( tabCoreUser.getUserName(), session );
//                return new ResponseEntity<>(ResponseDto.responseFail("该用户已经登录,不允许重复登录"), HttpStatus.OK);
//            }
//            /**
//             * 该账号未被登陆
//             */
//            else
//            {
//                SessionListener.sessionMap.put( tabCoreUser.getUserName(), session );
//            }
            return new ResponseEntity<>(ResponseDto.responseOK(""), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResponseDto.responseFail("用户名或密码错误"), HttpStatus.OK);
    }



    private String entityToString(HttpEntity entity) throws IOException {
        String result = null;
        if(entity != null)
        {
            long lenth = entity.getContentLength();
            if(lenth != -1 && lenth < 2048)
            {
                result = EntityUtils.toString(entity,"UTF-8");
            }else {
                InputStreamReader reader1 = new InputStreamReader(entity.getContent(), "UTF-8");
                CharArrayBuffer buffer = new CharArrayBuffer(2048);
                char[] tmp = new char[1024];
                int l;
                while((l = reader1.read(tmp)) != -1) {
                    buffer.append(tmp, 0, l);
                }
                result = buffer.toString();
            }
        }
        return result;
    }

    /**
     * get请求，参数放在map里
     * @param url 请求地址
     * @param map 参数map
     * @return 响应
     */
    public String getMap(String url,Map<String,String> map)
    {
        String result = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        for(Map.Entry<String,String> entry : map.entrySet())
        {
            pairs.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
        }
        CloseableHttpResponse response = null;
        try {
            URIBuilder builder = new URIBuilder(url);
            builder.setParameters(pairs);
            HttpGet get = new HttpGet(builder.build());
            response = httpClient.execute(get);
            if(response != null && response.getStatusLine().getStatusCode() == 200)
            {
                HttpEntity entity = response.getEntity();
                result = entityToString(entity);
            }
            return result;
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                httpClient.close();
                if(response != null)
                {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }


    /**
     * 退出登录
     * @author lishaochuan
     * @create 2017/4/11 12:27
     * @param
     * @return
     */
    @RequestMapping(value = "/logout")
    public String userLogout(HttpServletRequest request) {
        request.getSession().invalidate();
        return "redirect:/login";
    }

    /**
     * 跳转错误页面
     * @author lishaochuan
     * @create 2017/4/11 12:27
     * @param
     * @return
     */
    @RequestMapping(value = "/error")
    public String redirectError(HttpServletRequest request) {
        request.getSession().invalidate();
        return "error/error";
    }

    /**
     * 跳转未授权页面
     * @author lishaochuan
     * @create 2017/4/11 12:27
     * @param
     * @return
     */
    @RequestMapping(value="/noAuthority")
    public String redirect403Error(HttpServletRequest request){
        return "error/403";
    }
    
    @RequestMapping(method = RequestMethod.GET,value = "/logintest")
    public ResponseEntity<ResponseDto> logintest(HttpServletRequest request, Model model){
        String loginName = (String)request.getParameter("loginName");
        String password = (String)request.getParameter("password");
        LogUtil.info(LOGGER, "loginName:{},password:{}", loginName,password);
        TabCoreUserEntity tabCoreUser = userService.login(loginName, password);
        if(!Check.isNullObj(tabCoreUser)){
            UserUtil.setUser2Session(new CurrentUserVo(tabCoreUser));
            
            
            List<String> list = new ArrayList<String>();
            list.add("1");
            list.add("2");
            list.add("3");
            return new ResponseEntity<>(ResponseDto.responseOK(tabCoreUser), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResponseDto.responseFail(""), HttpStatus.OK);
    }

}
